package com.sztu.controller;

import com.sztu.service.BorrowService;
import com.sztu.utils.Result;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class BorrowController {
    private final BorrowService borrowService;

    private static Logger logger = Logger.getLogger(BorrowController.class);

    public BorrowController(BorrowService borrowService) {
        this.borrowService = borrowService;
    }

    @PostMapping("/borrow")
    public Result borrow(@RequestBody Map<String,Object> borrowInfo){
        try {
            borrowService.borrow(borrowInfo);
            return new Result().setCode(200).setMessage("借用申请成功，请等待申请通过");
        }catch (Exception e){
            logger.error(e);
            return new Result().setCode(202).setMessage("借用失败");
        }
    }

    @GetMapping("/getApproveList/{userId}")
    public Result getApproveList(@PathVariable("userId")Long userId){
        Map<String,Object> data=new LinkedHashMap<String,Object>();
        data.put("tableData",borrowService.getNeedsApprove(userId));
        return new Result().setCode(200).setData(data);
    }

    @GetMapping("/getApprovals/{userId}")
    public Result getApprovals(@PathVariable("userId")Long userId){
        Map<String,Object> data=new LinkedHashMap<String,Object>();
        data.put("tableData",borrowService.getApprovals(userId));
        return new Result().setCode(200).setData(data);
    }

    @PostMapping("/approve")
    public Result approve(@RequestBody Map<String,Object> approveInfo){
        try {
            borrowService.approve(approveInfo);
            return new Result().setCode(200).setMessage("审批消息修改成功");
        }catch (Exception e){
            logger.error(e);
            return new Result().setCode(202).setMessage("审批消息修改失败");
        }
    }

    @PostMapping("/confirmReturn")
    public Result confirmReturn(@RequestBody Map<String,Object> returnInfo){
        try {
            borrowService.returnDevice(returnInfo);
            return new Result().setCode(200).setMessage("已经确认归还信息");
        }catch (Exception e){
            logger.error(e);
            return new Result().setCode(202).setMessage("确认归还信息失败");
        }
    }
}
